package com.mavenq.fly.utils.excelv3;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.*;
import java.util.stream.Collectors;

public class ValidationExample {

    public static void main(String[] args) {
        try {
            new ValidationExample().runDemo();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void runDemo() throws Exception {
        // 创建测试文件
        createTestExcelFile();

        // 执行带校验的导入
        importWithValidationDemo();
    }

    private void createTestExcelFile() throws FileNotFoundException {
        List<User> userList = Arrays.asList(
                new User("张三", 25, "zhangsan@example.com", new Date()),
                new User("", 30, "invalid-email", new Date()), // 无效数据
                new User("李四", 200, "lisi@example.com", new Date()), // 年龄超限
                new User("王五", 28, "wangwu@example.com", new Date())
        );

        String[] headers = {"姓名", "年龄", "邮箱", "创建时间"};
        String[] fieldNames = {"name", "age", "email", "createTime"};

        FileOutputStream fos = new FileOutputStream("validation_test.xlsx");
        ExcelUtil.exportToExcel(userList, headers, fieldNames, "测试数据", fos, true);
        System.out.println("创建测试文件: validation_test.xlsx");
    }

    private void importWithValidationDemo() throws FileNotFoundException {
        System.out.println("\n=== 带校验的导入示例 ===");

        FileInputStream fis = new FileInputStream("validation_test.xlsx");

        ExcelImportConfig<User> config = new ExcelImportConfig<>(User.class)
                .columnMapping("姓名", "name")
                .columnMapping("年龄", "age")
                .columnMapping("邮箱", "email")
                .columnMapping("创建时间", "createTime")
                .requiredFields("name", "email") // 设置必填字段
                .addFieldValidator("name", (value, fieldName, rowIndex, columnIndex) -> {
                    // 姓名校验
                    List<String> errors = new ArrayList<>();
                    if (value == null || value.toString().trim().isEmpty()) {
                        errors.add("姓名不能为空");
                    } else if (value.toString().length() > 20) {
                        errors.add("姓名长度不能超过20个字符");
                    }
                    return errors;
                })
                .addFieldValidator("age", (value, fieldName, rowIndex, columnIndex) -> {
                    // 年龄校验
                    List<String> errors = new ArrayList<>();
                    if (value != null) {
                        try {
                            int age = Integer.parseInt(value.toString());
                            if (age < 0 || age > 150) {
                                errors.add("年龄必须在0-150之间");
                            }
                        } catch (NumberFormatException e) {
                            errors.add("年龄必须是有效的数字");
                        }
                    }
                    return errors;
                })
                .addFieldValidator("email", (value, fieldName, rowIndex, columnIndex) -> {
                    // 邮箱校验
                    List<String> errors = new ArrayList<>();
                    if (value != null && !value.toString().trim().isEmpty()) {
                        String email = value.toString();
                        if (!email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
                            errors.add("邮箱格式不正确");
                        }
                    }
                    return errors;
                })
                .addBusinessValidator((user, rowIndex) -> {
                    // 业务校验 - 检查姓名和邮箱的关联性
                    List<ImportErrorDetail> errors = new ArrayList<>();
                    if (user.getName() != null && user.getEmail() != null) {
                        String name = user.getName().toLowerCase();
                        String email = user.getEmail().toLowerCase();
                        if (!email.contains(name)) {
                            errors.add(new ImportErrorDetail(rowIndex, 2, "测试数据",
                                    "email", user.getEmail(), "邮箱应该包含姓名",
                                    ImportErrorDetail.ErrorType.BUSINESS_ERROR));
                        }
                    }
                    return errors;
                });

        // 执行导入
        ImportResult<User> result = ExcelUtil.importExcelWithValidation(fis, config, true);

        // 输出结果
        System.out.println(result.getErrorSummary());
        System.out.println("\n成功导入的数据:");
        result.getSuccessData().forEach(user -> System.out.println("  " + user));

        if (!result.getErrors().isEmpty()) {
            System.out.println("\n详细错误信息:");
            result.getErrors().forEach(error ->
                    System.out.println("  " + error.getFullErrorMessage()));
        }

        // 按错误类型分组显示
        Map<ImportErrorDetail.ErrorType, List<ImportErrorDetail>> errorsByType =
                result.getErrors().stream().collect(Collectors.groupingBy(ImportErrorDetail::getErrorType));

        errorsByType.forEach((type, errors) -> {
            System.out.println("\n" + type + " 错误:");
            errors.forEach(error ->
                    System.out.println("  " + error.getExcelPosition() + " - " + error.getErrorMessage()));
        });
    }

    // 实体类
    static class User {
        private String name;
        private Integer age;
        private String email;
        private Date createTime;
        private Boolean status;

        // 构造方法
        public User() {
        }

        public User(String name, Integer age, String email, Date createTime) {
            this.name = name;
            this.age = age;
            this.email = email;
            this.createTime = createTime;
            this.status = true;
        }

        // getter and setter
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public Date getCreateTime() {
            return createTime;
        }

        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }

        public Boolean getStatus() {
            return status;
        }

        public void setStatus(Boolean status) {
            this.status = status;
        }

        @Override
        public String toString() {
            return "User{name='" + name + "', age=" + age + ", email='" + email + "'}";
        }
    }
}